/**
 * Copyright 2007 Luke Pillow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.orsomethinglikethat.flex.filemaker.request
{
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoader;
	import flash.events.Event;
	import mx.controls.Alert;
	import flash.net.URLRequestHeader;
	import mx.utils.Base64Encoder;
	import com.orsomethinglikethat.flex.filemaker.FileMaker;
	import com.orsomethinglikethat.flex.filemaker.command.Command;
	import com.abdulqabiz.net.HTTPURLLoader;
	
	public class FileMakerRequest
	{
		private var fileMaker:FileMaker;
		private var queryParameters:Array = new Array();
		private var command:Command;
		
		private var serverUrl:String;		
		public var resultHandler:Function;
		public var errorHandler:Function;
		
		public function FileMakerRequest( fileMaker:FileMaker, command:Command )
		{
			super();
			
			this.fileMaker = fileMaker;
			this.command = command;
			
			this.queryParameters = this.queryParameters.concat( this.command.parameters );
			this.queryParameters.push( new DatabaseParameter( this.fileMaker.database ) );
			this.queryParameters.push( new LayoutParameter( this.command.layout ) );
		}
		
		private function buildURL():String
		{
			var url:String = this.fileMaker.serverUrl + "?" + this.command.name;

			for each( var parameter:Parameter in this.queryParameters )
			{
				url += "&" + parameter.toString();
			}
			return url;
		}
		
		private function newRequest():URLRequest
		{
			var urlRequest:URLRequest = new URLRequest();
			
			urlRequest.requestHeaders.push( new URLRequestHeader("Authorization", "Basic " + this.fileMaker.credentials ) );
			
			//urlRequest.requestHeaders.push( new URLRequestHeader("BAM", "BAM" ) );
			
			urlRequest.method = URLRequestMethod.POST;
			
			urlRequest.url = this.buildURL();
			
			
			return urlRequest;
		}
		
		public function execute( resultHandler:Function, errorHandler:Function ):void
		{
			var request:URLRequest = this.newRequest();
			
			
			var urlLoader:HTTPURLLoader = new HTTPURLLoader();
			urlLoader.addEventListener( "complete", resultHandler );
			urlLoader.load( request );
			
		}
		
	}
}